import { HTTP } from '../util/http'
import { LikeModel } from './like'

let likeModel = new LikeModel()

const storageKey = {
  latestIndex: 'latestIndex',
}

class ClassicModel extends HTTP {
  getLatest(sCallback) {
    this.request({
      url: 'classic/latest',
      success: (res) => {
        sCallback(res)
        let index = res.index
        this.setLatestIndex(index)
        let key = this.getKey(index)
        wx.setStorageSync(key, res)
      },
    })
  }

  getNext(index, sCallback) {
    let key = this.getKey(index + 1)
    let classic = wx.getStorageSync(key)
    if (!classic) {
      this.request({
        url: 'classic/' + index + '/next',
        success: (res) => {
          wx.setStorageSync(this.getKey(res.index), res)
          sCallback(res)
        },
      })
    } else {
      likeModel.getClassicLikeStatus(classic.id, classic.type, (res) => {
        classic.fav_nums = res.fav_nums
        classic.like_status = res.like_status
        sCallback(classic)
      })
    }
  }

  getPrevious(index, sCallback) {
    let key = this.getKey(index - 1)
    let classic = wx.getStorageSync(key)
    if (!classic) {
      this.request({
        url: 'classic/' + index + '/previous',
        success: (res) => {
          wx.setStorageSync(this.getKey(res.index), res)
          sCallback(res)
        },
      })
    } else {
      likeModel.getClassicLikeStatus(classic.id, classic.type, (res) => {
        classic.fav_nums = res.fav_nums
        classic.like_status = res.like_status
        sCallback(classic)
      })
    }
  }

  getMyFavor(success) {
    const params = {
      url: 'classic/favor',
      success: success,
    }
    this.request(params)
  }

  isFirst(index) {
    return index == 1
  }

  isLatest(index) {
    return index == wx.getStorageSync(storageKey.latestIndex)
  }

  setLatestIndex(index) {
    wx.setStorageSync(storageKey.latestIndex, index)
  }

  getKey(index) {
    return 'classic-' + index
  }
}

export { ClassicModel }
